package com.ruoyi.ahs.util;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.ahs.cache.AhsCache;
import com.ruoyi.system.domain.ahs.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Objects;

/**
 * RequestManager
 *
 * @author 辛凤文
 * @since 1.0
 */
@Component
@Slf4j
public class AhsUtils {

    private static final RestTemplate ahsRestTemplate = new RestTemplate();

    private static final String URL_SEARCH = "https://dubai.aihuishou.com/ahs-yanxuan-service/products/search-goods-v2";
    private static final String URL_CREATE_ORDER = "https://dubai.aihuishou.com/ahs-yanxuan-service/sale-orders/yanxuan/create?decode__1903=eqjxBDuDc7itm4xBqDwCDUxxAxwy1q%3D%3DTq4D";
    private static final String URL_ADDRESS_LIST = "https://dubai.aihuishou.com/dubai-gateway/user-address/list";
    private static final String CATEGORY_BRAND_LIST = "https://dubai.aihuishou.com/ahs-yanxuan-service/products/category-and-brand?scene=YANXUAN_HOME&gaeaCategoryId=%d";
    private static final String PPVASSOCIATION = "https://dubai.aihuishou.com/ahs-yanxuan-service/products/ppn-list?gaeaCategoryId=%d&gaeaBrandId=%d&gaeaProductId=%d";
    private static final String PRODUCT_LIST = "https://dubai.aihuishou.com/ahs-yanxuan-service/products/product?gaeaCategoryId=%d&gaeaBrandId=%d";

    /**
     * 搜索商品
     * @param productSearch
     * @return
     */
    public static SearchResult search(ProductSearch productSearch) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<ProductSearch> entity = new HttpEntity<>(productSearch, headers);
        SearchResult searchResult = null;
        log.info("搜索监控参数：{}", JSONObject.toJSONString(productSearch));
        try {
            ResponseEntity<SearchResult> response = ahsRestTemplate.exchange(
                    URL_SEARCH,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<SearchResult>() {
                    });
            searchResult = response.getBody();
            log.info("查询商品结果：{}", JSONObject.toJSONString(searchResult));
            // 处理返回的SearchResult
        } catch (Exception e) {
            log.info("查询商品结果：{}", JSONObject.toJSONString(searchResult), e);
        }
        return searchResult;
    }

    /**
     * 创建订单
     * @return
     */
    public static OrderResult createOrder(Order order) {
        log.info("请求下单参数{}", JSONObject.toJSONString(order));
        if (order.getAddressId() == null) {
            order.setAddressId(AhsCache.getAddressId());
        }
        HttpHeaders headers = AhsCache.getHttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Order> entity = new HttpEntity<>(order, headers);
        OrderResult orderResult = null;
        try {
            ResponseEntity<OrderResult> response = ahsRestTemplate.exchange(
                    URL_CREATE_ORDER,
                    HttpMethod.POST,
                    entity,
                    new ParameterizedTypeReference<OrderResult>() {
                    });
            orderResult = response.getBody();
            // 处理返回的SearchResult
            log.info("请求下单结果：{}", Objects.isNull(orderResult) ? "" : JSONObject.toJSONString(orderResult));
        } catch (Exception e) {
            e.printStackTrace();
            // TODO 处理异常，增加程序健壮性
        }
        return orderResult;
    }

    /**
     * 获取收获地址列表
     * @return
     */
    public static List<ReceiverAddress> fetchAddressList() {
        HttpHeaders headers = AhsCache.getHttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        AhsResult<List<ReceiverAddress>> result = null;
        try {
            ResponseEntity<AhsResult<List<ReceiverAddress>>> response = ahsRestTemplate.exchange(
                    URL_ADDRESS_LIST,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<AhsResult<List<ReceiverAddress>>>() {
                    });
            result = response.getBody();
            // 处理返回的SearchResult
        } catch (Exception e) {
            throw new RuntimeException("获取地址失败");
        }
        if (result.isSuccess()) {
            return result.getData();
        } else {
            throw new RuntimeException(result.getResultMessage());
        }
    }

    public Object login(LoginRequestForm loginRequestForm) {
        //TODO 待实现
        return null;
    }

    public static void main(String[] args) {
        List<AhsCategoryAndBrand> categoryBrand = getCategoryBrand(655L);
        System.out.println(JSONObject.toJSONString(categoryBrand));
    }

    /**
     * 获取分类品牌列表
     * @return
     */
    public static List<AhsCategoryAndBrand> getCategoryBrand(Long gaeaCategoryId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        AhsResult<List<AhsCategoryAndBrand>> result = null;
        try {
            ResponseEntity<AhsResult<List<AhsCategoryAndBrand>>> response = ahsRestTemplate.exchange(
                    String.format(CATEGORY_BRAND_LIST, gaeaCategoryId),
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<AhsResult<List<AhsCategoryAndBrand>>>() {
                    });
            result = response.getBody();
        } catch (Exception e) {
            log.error("获取分类和品牌列表失败，请求地址：{}，响应体：{}，异常信息：", String.format(CATEGORY_BRAND_LIST, gaeaCategoryId), result,
                    e);
            throw new RuntimeException("获取分类和品牌列表失败");
        }
        log.info("获取分类和品牌列表：{}", JSONObject.toJSONString(result));
        if (result.isSuccess()) {
            return result.getData();
        } else {
            throw new RuntimeException(result.getResultMessage());
        }
    }

    /**
     * 获取产品型号选项列表
     * @param gaeaCategoryId
     * @param gaeaBrandId
     * @return
     */
    public static List<AhsProduct> getProduct(Long gaeaCategoryId, Long gaeaBrandId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        AhsResult<List<AhsProduct>> result;
        String format = String.format(PRODUCT_LIST, gaeaCategoryId, gaeaBrandId);
        try {
            ResponseEntity<AhsResult<List<AhsProduct>>> response = ahsRestTemplate.exchange(
                    format,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<AhsResult<List<AhsProduct>>>() {
                    });
            result = response.getBody();
            // 处理返回的SearchResult
        } catch (Exception e) {
            throw new RuntimeException("获取产品型号失败");
        }
        log.info("获取产品型号：{}", JSONObject.toJSONString(result));
        if (result.isSuccess()) {
            return result.getData();
        } else {
            throw new RuntimeException(result.getResultMessage());
        }
    }

    /**
     * 获取产品其他参数选项列表
     * @param gaeaCategoryId
     * @param gaeaBrandId
     * @param gaeaProductId
     * @return
     */
    public static AhsPpnPpvAssociationVO getPpvAssociation(Long gaeaCategoryId, Long gaeaBrandId, Long gaeaProductId) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<?> entity = new HttpEntity<>(headers);
        AhsResult<AhsPpnPpvAssociationVO> result;
        String format = String.format(PPVASSOCIATION, gaeaCategoryId, gaeaBrandId, gaeaProductId);
        try {
            ResponseEntity<AhsResult<AhsPpnPpvAssociationVO>> response = ahsRestTemplate.exchange(
                    format,
                    HttpMethod.GET,
                    entity,
                    new ParameterizedTypeReference<AhsResult<AhsPpnPpvAssociationVO>>() {
                    });
            result = response.getBody();
        } catch (Exception e) {
            throw new RuntimeException("获取参数选项失败");
        }
        log.info("获取参数选项：{}", JSONObject.toJSONString(result));
        if (result.isSuccess()) {
            return result.getData();
        } else {
            throw new RuntimeException(result.getResultMessage());
        }
    }

}
